package resp

import (
	"github.com/gogf/gf/encoding/gjson"
	"github.com/gogf/gf/errors/gerror"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/util/gconv"
)

// JsonResponse 数据返回通用JSON数据结构
type JsonResponse struct {
	Code     int         `json:"code"`               // 错误码
	Message  string      `json:"message"`            // 提示信息
	Data     interface{} `json:"data,omitempty"`     // 返回数据(业务接口定义具体数据结构)
	Redirect string      `json:"redirect,omitempty"` // 引导客户端跳转到指定路由
}

// JsonResp 返回JSON数据。
func JsonResp(code int, msg string, data ...interface{}) *JsonResponse {
	responseData := interface{}(nil)
	if len(data) > 0 {
		responseData = data[0]
	}
	codeMsgs := GetCodeMsg(code, msg)

	response := &JsonResponse{
		//ID:      r.GetCtxVar("RequestId").String(),
		Code:    code,
		Message: codeMsgs,
		Data:    responseData,
	}
	return response
}

func ApiResponse(r *ghttp.Request, res interface{}) {
	Map := gjson.New(res).Map()
	Map["id"] = r.GetCtxVar("request_id")
	r.Response.WriteJson(Map)
	r.Exit()
}

func Success(data interface{}) *JsonResponse {
	return JsonResp(success, "", data)
}

func Failure(code int, err error) *JsonResponse {

	return JsonResp(code, "", err)
}

func dataReturn(r *ghttp.Request, code int, req ...interface{}) *JsonResponse {
	var msg string
	var data interface{}
	if len(req) > 0 {
		msg = gconv.String(req[0])
	}
	if len(req) > 1 {
		data = req[1]
	}
	//msg = GetCodeMsg(code, msg)
	if code != success && !gconv.Bool(r.GetCtxVar("api_code")) {
		code = generalFail
	}
	response := &JsonResponse{
		//ID:      r.GetCtxVar("RequestId").String(),
		Code:    code,
		Message: msg,
		Data:    data,
	}
	r.SetParam("apiReturnRes", response)
	return response
}

func SuccessWithData(r *ghttp.Request, data interface{}) {
	res := dataReturn(r, success, "ok", data)
	_ = r.Response.WriteJsonExit(res)
}

func FailureWithData(r *ghttp.Request, code int, err error, data interface{}) {
	res := dataReturn(r, code, err.Error(), data)
	_ = r.Response.WriteJsonExit(res)
}

func Code(r *ghttp.Request, err error) {
	//res := dataReturn(r, gerror.Code(err).Code(), gerror.Code(err).Message(), gerror.Code(err).Detail())
	res := dataReturn(r, gerror.Code(err).Code(), err.Error(), gerror.Code(err).Detail())
	_ = r.Response.WriteJsonExit(res)
}

// Fatal 致命错误
func Fatal(r *ghttp.Request) {
	res := dataReturn(r, 500)
	_ = r.Response.WriteJsonExit(res)
}

// Sign 签名错误
func Sign(r *ghttp.Request, err error) {
	res := dataReturn(r, signFail, err.Error())
	_ = r.Response.WriteJsonExit(res)
}

// NoPower 认证失败
func NoPower() *JsonResponse {
	response := &JsonResponse{
		//ID:      r.GetCtxVar("RequestId").String(),
		Code:    noPower,
		Message: "没有权限",
	}
	return response
}
